/*
 * Copyright (c) 2001 Boris Pruessmann and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Common Public License v0.5
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors:
 *    Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.p4eclipse.ui.action;

import net.sourceforge.p4eclipse.core.PerforceRepositoryProvider;
import net.sourceforge.p4eclipse.ui.PerforceUIPlugin;
import net.sourceforge.p4eclipse.ui.sync.PerforceSyncCompareInput;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.action.IAction;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.actions.TeamAction;
import org.eclipse.team.internal.ui.sync.SyncView;
import org.eclipse.ui.PartInitException;

/**
  * @version 	1.0
  * @author		<a href="mailto:bpruessmann@users.sourceforge.net">Boris Pruessmann</a>
  */
public class SyncAction extends TeamAction
{
	/*
	 * @see TeamAction#isEnabled()
	 */
	protected boolean isEnabled() throws TeamException
	{
		IResource[] resources = getSelectedResources();
		if (resources.length == 0) 
			return false;
			
		for (int i = 0; i < resources.length; i++) 
		{
			RepositoryProvider tempProvider = RepositoryProvider.getProvider(resources[i].getProject());
			if (tempProvider == null || !tempProvider.getID().equals(PerforceUIPlugin.getTypeId()))
				return false;
				
			PerforceRepositoryProvider provider = (PerforceRepositoryProvider)tempProvider;
			if (provider.isCheckedOut(resources[i]))
				return false;
				
			if (!provider.hasRemote(resources[i])) 
				return false;				
		}
		return true;
	}

	/*
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action)
	{
		IResource[] resources = getSelectedResources();

		SyncView view = (SyncView)PerforceUIPlugin.getActivePage().findView(SyncView.VIEW_ID);
		if (view == null) 
			view = SyncView.findInActivePerspective();
		
		if (view != null)
		{
			try 
			{
				PerforceUIPlugin.getActivePage().showView(SyncView.VIEW_ID);
			} 
			catch (PartInitException e) 
			{
				PerforceUIPlugin.getPlugin().log(e.getStatus());
			}
			
			view.showSync(new PerforceSyncCompareInput(resources));
		}		
	}

}
